package com.siloam.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 验证码工具类
 * 生成验证码图片和取得验证码字符串
 * 
 * 日期:2014-3-19
 * @author rzpeng
 * 
 */
public class Captcha {

	private String charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
	private int num = 4;
	private int width = 70;
	private int height = 30;
	private Random random = new Random();

	public Captcha(){
	}
	
	public Captcha(int width, int height){
		this.width = width;
		this.height = height;
	}
	
	/**
	 * 验证码字符集，默认是26个大写字母和数字
	 * 
	 * @return
	 */
	public String getCharSet() {
		return charSet;
	}

	public void setCharSet(String charSet) {
		this.charSet = charSet;
	}

	/**
	 * 验证码字符数,默认4个
	 * 
	 * @return
	 */
	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	/**
	 * 验证码图片宽带,默认70
	 * 
	 * @return
	 */
	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	/**
	 * 验证码高度,默认30
	 * 
	 * @return
	 */
	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	/**
	 * 取得验证码字符串
	 * 
	 * @return
	 */
	public String getCodes() {
		char[] codes = new char[num];
		for (int i = 0; i < num; i++) {
			int index = random.nextInt(charSet.length());
			codes[i] = charSet.charAt(index);
		}
		return new String(codes);
	}

	/**
	 * 取得验证码所对应的图片
	 * 
	 * @param codes
	 *            验证字符串
	 * @return
	 */
	public BufferedImage getBufferedImage(String codes) {
		BufferedImage img = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g = img.createGraphics();
		// 设置背景
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, width, height);
		// 设置字体
		int fontHeight = (int) (height * 0.8);
		Font f = new Font("宋体", Font.BOLD + Font.ITALIC, fontHeight);
		g.setFont(f);
		// 画验证码
		for (int i = 0; i < codes.length(); i++) {
			g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
			g.drawString(String.valueOf(codes.charAt(i)), (int) (width / num * i), fontHeight);
		}
		// 画杂点
		for (int i = 0; i < 20; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			g.drawLine(x, y, x + random.nextInt(5), y + random.nextInt(5));
		}
		return img;
	}

}
